import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const roles = ref(userInfo.value?.roles || [])
  
  // 登录
  const loginAction = async (loginData) => {
    try {
      const res = await login(loginData)
      token.value = res.data.token
      userInfo.value = res.data.userInfo
      roles.value = res.data.userInfo.roles
      
      // 保存到本地存储
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
      
      return res
    } catch (error) {
      throw error
    }
  }
  
  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const res = await getUserInfo()
      userInfo.value = res.data
      roles.value = res.data.roles
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      return res
    } catch (error) {
      throw error
    }
  }
  
  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  // 判断是否有权限
  const hasRole = (role) => {
    return roles.value.includes(role)
  }
  
  return {
    token,
    userInfo,
    roles,
    loginAction,
    getUserInfoAction,
    logout,
    hasRole
  }
}) 